package com.sz.wallet_demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sz.wallet_demo.config.CurrContextHolder;
import com.sz.wallet_demo.mapper.BalanceChangeMapper;
import com.sz.wallet_demo.mapper.WalletMapper;
import com.sz.wallet_demo.model.BalanceChange;
import com.sz.wallet_demo.model.Wallet;
import com.sz.wallet_demo.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @author Ts-SuSu
 * @date 2023/9/2 7:10
 * @Description 钱包管理*
 * 1.查询用户钱包余额*
 * 2.用户消费100元的接口*
 * 3.用户退款20元*
 */

@RequestMapping("/wallet")
@RestController
@Api(tags = "钱包管理")
public class WalletController {

    private WalletMapper walletMapper;
    private BalanceChangeMapper balanceChangeMapper;

    public WalletController(WalletMapper walletMapper, BalanceChangeMapper balanceChangeMapper) {
        this.walletMapper = walletMapper;
        this.balanceChangeMapper = balanceChangeMapper;

    }


    @ApiOperation("钱包管理-获取当前用户钱包余额")
    @GetMapping("/getCurrUserWalletBalance")
    public Wallet getCurrWalletBalance() {
        //获取当前用户id
        Integer userId = CurrContextHolder.getNotNullCurr().getUser().getId();
        Wallet wallet = walletMapper.selectOne(new LambdaQueryWrapper<Wallet>().eq(Wallet::getUserId, userId));
        return wallet;
    }


    @ApiOperation("钱包管理-用户消费100元")
    @Transactional
    @PostMapping("/consume/{amountStr}")
    public Result UserConsumption(@PathVariable String amountStr) {
        BigDecimal amount = new BigDecimal(amountStr);
        //获取当前用户id
        Integer userId = CurrContextHolder.getNotNullCurr().getUser().getId();

        //获取当前用户钱包
        Wallet wallet = walletMapper.selectOne(new LambdaQueryWrapper<Wallet>().eq(Wallet::getUserId, userId));

        //定义结果
        int result = 0;

        if (wallet.getBalance().compareTo(amount) < 0) {
            return Result.fail("您的钱包余额不足,请先进行充值");
        }

        BigDecimal subtract = wallet.getBalance().subtract(amount);

        //消费金额,扣减钱包
        int update = walletMapper.update(wallet, new LambdaUpdateWrapper<Wallet>().eq(Wallet::getUserId, userId).set(Wallet::getBalance, subtract));
        if (update > 0) {
            result++;
        }
        BalanceChange balanceChange = new BalanceChange();
        balanceChange.setWalletId(wallet.getId());
        balanceChange.setChangeAmount(amount);
        balanceChange.setChangeType(2);
        balanceChange.setSerialNumber("XF" + System.currentTimeMillis());
        balanceChange.setChangeTime(new Date());
        //添加记录
        int insert = balanceChangeMapper.insert(balanceChange);
        if (insert > 0) {
            result++;
        }
        if (result < 2) {
            return Result.fail("消费失败,具体原因请咨询客服");
        }
        return Result.success(subtract, "消费成功");
    }

    @ApiOperation("钱包管理-用户退款20元")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params", value = "总字段包含以下所有字段 不传", required = false, dataType = "Map"),
            @ApiImplicitParam(name = "amountStr", value = "金额", required = true, dataType = "String"),
    })
    @Transactional
    @PostMapping("/refund")
    public Result UserRefund(@RequestParam Map<String, String> params) {
        BigDecimal amount = new BigDecimal(params.get("amountStr"));
        //获取当前用户id
        Integer userId = CurrContextHolder.getNotNullCurr().getUser().getId();

        Wallet wallet = walletMapper.selectOne(new LambdaQueryWrapper<Wallet>().eq(Wallet::getUserId, userId));

        //判断该用户的钱包金额是否满足退款
        BigDecimal balance = wallet.getBalance();
        if (balance.compareTo(amount) < 0) {
            return Result.fail("您的钱包余额不足，无法完成此次退款");
        }

        //定义结果
        int result = 0;

        BigDecimal subtract = balance.subtract(amount);

        //消费金额,扣减钱包
        int update = walletMapper.update(wallet, new LambdaUpdateWrapper<Wallet>().eq(Wallet::getUserId, userId).set(Wallet::getBalance, subtract));
        if (update > 0) {
            result++;
        }

        BalanceChange balanceChange = new BalanceChange();
        balanceChange.setWalletId(wallet.getId());
        balanceChange.setChangeAmount(amount);
        balanceChange.setChangeType(3);
        balanceChange.setSerialNumber("TK" + System.currentTimeMillis());
        balanceChange.setChangeTime(new Date());
        //添加记录
        int insert = balanceChangeMapper.insert(balanceChange);
        if (insert > 0) {
            result++;
        }
        if (result < 2) {
            return Result.fail("退款失败,具体原因请咨询客服");
        }
        return Result.success(subtract, "退款成功");
    }

}
